package com.example.paytext.service;

import cn.hutool.core.date.DateTime;
import com.example.paytext.contast.PayStatus;
import com.example.paytext.domain.PayRecord;
import com.example.paytext.dto.PayRecordDTO;
import com.example.paytext.mapper.PayMapper;
import com.example.paytext.mapper.PayRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class PayService {
    @Autowired
    private PayMapper payMapper;
    @Autowired
    private PayRecordMapper payRecordMapper;
    /**
     * 1.  查询用户钱包余额
     * @param userId
     * @return
     */
    public Map<String,Object> getUserSurMoney(String userId){
        return payMapper.getUserSurMoney(userId);
    }
    /**
     * 2. 用户消费100元的接口
     * 3. 用户退款20元接口
     */
    @Transactional
    public Map<String,Object> payMoney(PayRecordDTO dto){
        Map<String,Object> map=new HashMap<>();
        map.put("code",500);
        map.put("msg","用户Id不能为空");
        double payMoney=0D;
        if (!StringUtils.isEmpty(dto.getUserId())){
            //查询余额
            Map payMap= this.getUserSurMoney(dto.getUserId());
            //消费金额
            payMoney=Math.abs(dto.getMoney());
            dto.setCreatTime(DateTime.now());
            if (dto.getStatus()==PayStatus.PAY_RECHARGE||dto.getStatus()==PayStatus.PAY_DRAWBACK){
                dto.setMoney((double)payMap.get("money")+Math.abs(dto.getMoney()));
            }else if (dto.getStatus()==PayStatus.PAY_CONSUME){
                if ((double)payMap.get("money")<Math.abs(dto.getMoney())){
                    map.put("msg","余额不足");
                    return map;
                }
                dto.setMoney((double)payMap.get("money")-Math.abs(dto.getMoney()));
            }
            //扣除余额
            payMapper.updateMoney(dto);
            //添加消费记录
            dto.setMoney(Math.abs(payMoney));
            payRecordMapper.insertRecord(dto);
            map.put("code",200);
            map.put("msg","成功");
        }
        return map;
    }



}
